package com.lzw.bluetoothpractice.network;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.lzw.bluetoothpractice.AppConfig;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by yangzai on 2017/9/7.
 */

public class RetrofitManager {
    private static RetrofitManager mRetrofitManager;
    private static Retrofit mRetrofit;

    private RetrofitManager() {
        initRetrofit();
    }

    private RetrofitManager(String url) {
        initRetrofit(url);
    }

    public static synchronized RetrofitManager getInstance(String url) {
        try {
            if (mRetrofitManager == null) {
                mRetrofitManager = new RetrofitManager(url);
            } else {
                Log.d("Tag", "---");
            }
            return mRetrofitManager;
        } catch (IllegalArgumentException ii) {
            return null;
        }

    }

    public static synchronized RetrofitManager getInstance() {
        if (mRetrofitManager == null) {
            mRetrofitManager = new RetrofitManager();
        } else {
            Log.d("Tag", "---");
        }
        return mRetrofitManager;
    }

    public static Retrofit initRetrofit() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        builder.addInterceptor(new MyInterceptor());
        builder.retryOnConnectionFailure(true);
        if (AppConfig.DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("message", "收到响应：" + message);
                    if (TextUtils.isEmpty(message)) return;
                    String s = message.substring(0, 1);
                    //如果收到想响应是json才打印
                    if ("{".equals(s) || "[".equals(s)) {
                        Log.d("postRequest", "收到响应：" + message);
                    }
                }
            });
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(interceptor);
        }
        OkHttpClient client = builder.build();
        mRetrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        return mRetrofit;
    }

    public static Retrofit initRetrofit(String url) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        builder.addInterceptor(new MyInterceptor());
        builder.retryOnConnectionFailure(true);
        if (AppConfig.DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("message", "收到响应：" + message);
                    if (TextUtils.isEmpty(message)) return;
                    String s = message.substring(0, 1);
                    //如果收到想响应是json才打印
                    if ("{".equals(s) || "[".equals(s)) {
                        Log.d("postRequest", "收到响应：" + message);
                    }
                }
            });
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(interceptor);
        }
        OkHttpClient client = builder.build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        return mRetrofit;
    }

    public <T> T createReq(Class<T> reqServer) {
        return mRetrofit.create(reqServer);
    }

    static class MyInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {

            CacheControl.Builder builder = new CacheControl.Builder();
            //这个是控制缓存的最大生命时间   maxAge设置为0，不会取缓存，直接走网络。
            //此处设置缓存时间为两小时（两小时之内读取缓存）
            builder.maxAge(2, TimeUnit.HOURS);
            //缓存有效期一个月
            builder.maxStale(30, TimeUnit.DAYS);
            Request request = chain.request();

            //打印发送请求
            if (AppConfig.DEBUG) {
                Log.d("postRequest", "发送请求：" + request.url() + "-" + chain.connection() + "-" + request.headers());
            }
            Response response = chain.proceed(request);
            int maxStatle = 60 * 60 * 24 * 28;//28天
            return response.newBuilder().removeHeader("Pragma").header("Cache-Control", "public, only-if-cached, max-stale=" + maxStatle).build();
        }
    }
}

